#include "CryptoAgent.h"

#include <QTextCodec>
#include "crypt/CryptAES.h"
#include "crypt/CryptDES.h"
#include "crypt/CryptRC4.h"

CryptoAgent::CryptoAgent() :
	_type(CipherType::None),
	_crypt(NULL)
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("CP-1251"));
}

void CryptoAgent::setPassword(CipherType::Enum type, QString baseStr)
{
	_pass = baseStr;
	_type = type;

	int sz = _pass.size();
	if(sz == 0) return;

	if(!_crypt) delete _crypt;

	// Normalize pass
	switch(_type)
	{
	case CipherType::AES: // 128 bit
		_crypt = new CryptAES();
		if(sz >= 16) break;
		while(_pass.size() < 16){
			_pass.append(_pass.at(_pass.size()%sz));
		}
		break;
	case CipherType::DES: // 64 bit
		_crypt = new CryptDES();
		if(sz >= 8) break;
		while(_pass.size() < 8){
			_pass.append(_pass.at(_pass.size()%sz));
		}
		break;
	case CipherType::RC4: // 40 - 2048 bit
		_crypt = new CryptRC4();
		if(sz >= 5) break;
		while(_pass.size() < 5){
			_pass.append(_pass.at(_pass.size()%sz));
		}
		break;
	}

	_crypt->setPass(_pass.toLocal8Bit(),_pass.size());
}

QByteArray CryptoAgent::encrypt(QByteArray data)
{
	if(_pass.size() == 0) return data;
	if(_type == CipherType::None) return data;
	return _crypt->encrypt(data, true);
}

QByteArray CryptoAgent::decrypt(QByteArray data)
{
	if(_pass.size() == 0) return data;
	if(_type == CipherType::None) return data;
	return _crypt->encrypt(data, false);
}

void CryptoAgent::encryptNote(Note* note)
{
	note->setLogin( encrypt(note->getLogin()) );
	note->setPass( encrypt(note->getPass()) );
	note->setComment( encrypt(note->getComment()) );
	note->setUrl( encrypt(note->getUrl()) );
}

void CryptoAgent::decryptNote(Note* note)
{
	note->setLogin( decrypt(note->getLogin()) );
	note->setPass( decrypt(note->getPass()) );
	note->setComment( decrypt(note->getComment()) );
	note->setUrl( decrypt(note->getUrl()) );
}
